package com.sun.filesigndemo.common.security.Realm;


import com.sun.filesigndemo.bussiness.mapper.UserMapper;
import com.sun.filesigndemo.common.entity.User;
import com.sun.filesigndemo.common.security.Token.UserTokenToken;
import com.sun.filesigndemo.common.security.UserUtils;
import com.sun.filesigndemo.common.security.session.SessionDAO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * 系统安全认证实现类
 * @author Winkey
 * @version 2017-11-06
 */
@Service
public class UserTokenAuthorizingRealm extends AuthorizingRealm {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Value("${app.singleLogin}")
	Boolean singleLogin;
	@Autowired
	private SessionDAO sessionDao;
	@Autowired
	UserMapper userMapper;
	
	@Override
    public Class getAuthenticationTokenClass() {
        return UserTokenToken.class;
    }


	/**
	 * 认证回调函数, 登录时调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
		UserTokenToken token = (UserTokenToken) authcToken;

		// 校验用户名密码
		User user = token.getUser();
		if (user != null) {
			return new SimpleAuthenticationInfo(new Principal(user), user.getPhone(), getName());
		} else {
			return null;
		}
	}
	
	/**
	 * 获取权限授权信息，如果缓存中存在，则直接从缓存中获取，否则就重新获取， 登录成功后调用
	 */
	protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
		if (principals == null) {
            return null;
        }
		
        AuthorizationInfo info = null;

        info = (AuthorizationInfo)UserUtils.getCache(UserUtils.CACHE_AUTH_INFO);

        if (info == null) {
            info = doGetAuthorizationInfo(principals);
            if (info != null) {
            	UserUtils.putCache(UserUtils.CACHE_AUTH_INFO, info);
            }
        }

        return info;
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Principal principal = (Principal) getAvailablePrincipal(principals);
		// 获取当前已登录的用户
		if (singleLogin){
			Collection<Session> sessions = sessionDao.getActiveSessions(false, principal, UserUtils.getSession());
			if (sessions.size() > 0){
				// 如果是登录进来的，则踢出已在线用户
				if (SecurityUtils.getSubject().isAuthenticated()){
					for (Session session : sessions){
						sessionDao.delete(session);
					}
				}
				// 记住我进来的，并且当前用户已登录，则退出当前用户提示信息。
				else{
					SecurityUtils.getSubject().logout();
					throw new AuthenticationException("msg:账号已在其它地方登录，请重新登录。");
				}
			}
		}

		User user= userMapper.selectByPrimaryKey(principal.getLoginName());
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			// 补充获取用户权限逻辑
//			List<String> list= new ArrayList<>();
//			for (String menu : list){
//				if (StringUtils.isNotBlank(menu)){
//					// 添加基于Permission的权限信息
//					for (String permission : StringUtils.split(menu,",")){
//						info.addStringPermission(permission);
//					}
//				}
//			}

			// 添加用户角色信息
//			List<String>  roleList= new ArrayList<>();
//			roleList.add("admin");
//			for (String role : roleList){
//				info.addRole(role);
//			}
			// 更新登录IP和时间
			//getSystemService().updateUserLoginInfo(user);
			// 记录登录日志
			//LogUtils.saveLog(Servlets.getRequest(), "系统登录");
			info.addStringPermission("user");
			return info;
		} else {
			return null;
		}
	}

}
